﻿namespace DnD.UI.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.IO;
    using System.Configuration;

    public class NavigatorConfiguration
    {
        public string SchemaName { get; set; }
        public NavigatorItems Items { get; set; }

        public NavigatorConfiguration()
        {
            Items = new NavigatorItems();
        }

        public void LoadSchema(string filename)
        {
            FileStream strm = new FileStream(filename, FileMode.Open);
            LoadSchema(strm);
            strm.Close();
            strm.Dispose();
        }
        public void LoadSchema(Stream strm)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(strm);
            LoadSchema(doc);
        }
        public void LoadSchema(XmlDocument doc)
        {
            XmlNodeList list = doc.SelectNodes("NavigatorSchema/Schema");
            if (list.Count == 0)
                throw new Exception("Navigator schema invalid");
            foreach(XmlNode node in list[0].ChildNodes)
                LoadNode(node, Items);
        }
        private void LoadNode(XmlNode node, NavigatorItems parent)
        {
            LoadNode(node, parent, string.Empty);
        }
        private void LoadNode(XmlNode node, NavigatorItems parent, string IDPath)
        {
            NavigatorItem item = new NavigatorItem();
            item.ID = node.Name;
            item.IDPath = IDPath;
            if (node.Attributes["name"] != null)
                item.Name = node.Attributes["name"].Value;
            else
                item.Name = node.Name;
            if (node.Attributes["tooltip"] != null)
                item.ToolTip = node.Attributes["tooltip"].Value;
            else
                item.ToolTip = item.Name;
            if (node.Attributes["loadCollapsed"] != null)
            {
                try
                {
                    bool lc = bool.Parse(node.Attributes["loadCollapsed"].Value);
                    if (lc)
                        item.LoadCollapsed = true;
                }
                catch(Exception ex)
                {

                }
            }
            foreach (XmlNode child in node.ChildNodes)
                LoadNode(child, item.Children,item.FullID);
            parent.Add(item);
        }
    }
}
